<template>
  <div>
    <q-card class="no-shadow" bordered>
      <q-card-section class="text-h6">
        柱状图
        <q-btn
          icon="fa fa-download"
          class="float-right"
          @click="saveImage"
          flat
          dense
        >
          <q-tooltip>下载图表</q-tooltip>
        </q-btn>
      </q-card-section>
      <q-card-section>
        <VChart
          ref="barchart"
          :option="options"
          class="q-mt-md"
          :resizable="true"
          autoresize
          style="height: 300px"
        />
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import 'echarts';
import VChart from 'vue-echarts';
import { ref } from 'vue';
const barchart = ref<InstanceType<typeof VChart>>();
const options = {
  legend: {
    bottom: 10,
  },
  tooltip: {},
  dataset: {
    source: [
      ['产品', '2015', '2016', '2017'],
      ['拿铁', 43.3, 85.8, 93.7],
      ['奶茶', 83.1, 73.4, 55.1],
      ['可可', 86.4, 65.2, 82.5],
      ['核桃蛋糕', 72.4, 53.9, 39.1],
    ],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '20%',
    top: '5%',
    containLabel: true,
  },
  xAxis: { type: 'category' },
  yAxis: {},
  // Declare several bar series, each will be mapped
  // to a column of dataset.source by default.
  series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }],
};

const saveImage = () => {
  const linkSource = barchart.value?.getDataURL();
  const downloadLink = document.createElement('a');
  document.body.appendChild(downloadLink);
  downloadLink.href = linkSource as string;
  downloadLink.target = '_self';
  downloadLink.download = 'BarChart.png';
  downloadLink.click();
};
</script>

<style scoped></style>
